import json

import pandas as pd
import requests
from gm.api import get_previous_trading_date
from pandas.io.json import json_normalize

from ..common.date import is_today, date_format


def baidu_fivedays_fen_shi(code):
    """
    百度5日分时
    :param code:
    :return:
    """
    if code.startswith('sh'):
        code = code.replace('sh', '')
    else:
        code = code.replace('sz', '')

    url = 'https://finance.pae.baidu.com/selfselect/getstockquotation?code=' + code + '&isIndex=false&isBk=false&isBlock=false&group=quotation_fiveday_ab&finClientType=pc'
    real_price = requests.get(url)

    data = json.loads(real_price.text)
    data = data['Result']
    data = data['fivedays']
    return data


def teng_xun_fen_shi(code):
    """
    腾讯当日分时成交
    :param code:
    :return:
    """
    url = "https://web.ifzq.gtimg.cn/appstock/app/day/query?_var=fdays_data_" + code + "&code=" + code
    content = requests.get(url)
    replace = "fdays_data_" + code + "="
    rc = content.text.replace(replace, "")
    data = json.loads(rc)
    return data['data'][code]['data']


def jue_jin_fen_shi_context_data(context, code, date):
    """
    掘金指定日期的分时数据
    :param context:
    :param code:
    :param date:
    :return:
    """
    data = context.data(code, '60s', 240)
    sub_data = data[data['bob'] >= date]
    x = sub_data.copy()
    x.loc[:, 'avg'] = round(sub_data['amount'].cumsum() / sub_data['volume'].cumsum(), 2)
    return x


def is_full_price_up_fen_shi(fen_shi_data_df):
    """
    价格是否全部运行在分时线上方
    :param fen_shi_data_df:
    :return:
    """
    down_fenshi_data_df = fen_shi_data_df[fen_shi_data_df['close'] < fen_shi_data_df['avg']]
    if len(down_fenshi_data_df > 0):
        return False
    return True


def get_five_days_fen_shi_max_price_baidu(code):
    """
    百度5日分时成交量最大价格
    """
    url = 'https://finance.pae.baidu.com/selfselect/getstockquotation?code=' + code + '&isIndex=false&isBk=false&isBlock=false&group=quotation_fiveday_ab&finClientType=pc'
    real_price = requests.get(url)
    is_full_up_real_price = False
    data = json.loads(real_price.text)
    data = data['Result']
    data = data['Result']
    data = data['Result']
    data = data['fivedays']

    data_pd = pd.DataFrame()

    for content in data:
        bool_is_today = is_today(content['date'])
        pds = json_normalize(content['priceinfos'])
        if len(data_pd) == 0:
            data_pd = pds
        else:
            data_pd = pd.merge(data_pd, pds, how='outer')

        if bool_is_today:
            pds = pds[(pds['price'] < pds['avgPrice'])]
            if len(pds) == 0:
                is_full_up_real_price = True

    data_types_dict = {'price': float, 'volume': float}
    data_pd = data_pd.astype(data_types_dict)
    data_pd['amounts'] = data_pd['price'] * data_pd['volume']
    data_pd = data_pd.groupby(['price'], as_index=False)['amounts'].sum()
    data_pd = data_pd.sort_values(by='amounts')
    max_amount = data_pd['amounts'].max()
    max_pd = data_pd[data_pd['amounts'] == max_amount]
    max_price = max_pd['price']
    return max_price, is_full_up_real_price


def max_vol_yesterday_baidu(code, context):
    """
    百度昨日分时最大成交量
    :param code:
    :param context:
    :return:
    """
    date3 = context.now.strftime("%Y%m%d")
    pre_date = get_previous_trading_date(exchange='SZSE', date=date3)
    return max_vol_baidu(code, pre_date)


def max_vol_today_baidu(code, context):
    date3 = context.now.strftime("%Y%m%d")
    return max_vol_baidu(code, date3)


def max_vol_yesterday_without_spide_baidu(data, context):
    date3 = context.now.strftime("%Y%m%d")
    pre_date = get_previous_trading_date(exchange='SZSE', date=date3)
    return max_vol_without_spide_baidu(data, pre_date)


def max_vol_today_without_spide_baidu(data, context):
    date3 = context.now.strftime("%Y-%m-%d")
    return max_vol_without_spide_baidu(data, date3)


def max_vol_baidu(code, date):
    data = baidu_fivedays_fen_shi(code)
    return max_vol_without_spide_baidu(data, date)


def max_vol_without_spide_baidu(data, date):
    data_pd = pd.DataFrame()
    for content in data:
        if content['date'] != date:
            continue
        pds = json_normalize(content['priceinfos'])
        if len(data_pd) == 0:
            data_pd = pds
        else:
            data_pd = pd.merge(data_pd, pds, how='outer')

    data_types_dict = {'price': float, 'volume': float}
    data_pd = data_pd.astype(data_types_dict)
    data_pd = data_pd.sort_values(by='volume')
    max_volume = data_pd['volume'].max()
    return max_volume


def txfb_trade(code):
    url = 'https://stock.gtimg.cn/data/index.php?appn=detail&action=data&c=' + code + '&p=0'
    content = requests.get(url)
    replace = "v_detail_data_" + code + "="
    rc = content.text.replace(replace, "")
    data = json.loads(rc)
    return data


def tx_jhjj_vol(code):
    data = txfb_trade(code)
    vol = data[1].split('|')[0].split('/')[4]
    return vol


def max_vol_yesterday_without_spide_tx(code, tengxun_fenshi_data, context):
    date3 = context.now.strftime("%Y%m%d")
    pre_date = get_previous_trading_date(exchange='SZSE', date=date3)
    pre_date = date_format(pre_date, "%Y-%m-%d", "%Y%m%d")
    return max_vol_without_spide_tx(code, tengxun_fenshi_data, pre_date)


def max_vol_today_without_spide_tx(code, tengxun_fenshi_data, context):
    date3 = context.now.strftime("%Y%m%d")
    return max_vol_without_spide_tx(code, tengxun_fenshi_data, date3)


def max_vol_without_spide_tx(code, data, date):
    data_pd = pd.DataFrame(columns=['time', 'price', 'vol', 'amount', 'date', 'code'])
    data = data['data']
    data = data[code]
    data = data['data']
    for content in data:
        if content['date'] != date:
            continue
        data_list = content['data']
        for info in data_list:
            arr = info.split(" ")
            trade_time = arr[0]
            price = arr[1]
            vol = arr[2]
            amount = arr[3]

            ppa = pd.DataFrame(
                {'time': [trade_time], 'price': [price], 'vol': [vol], 'amount': [amount], 'date': [date],
                 'code': [code]})
            data_pd = pd.concat([ppa, data_pd], ignore_index=True)

    data_pd[['vol', 'price']] = data_pd[['vol', 'price']].astype(float)
    max_volume = data_pd['vol'].max()
    return max_volume
